package com.mbt.deal.api;


import com.mbt.deal.util.LogUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author 赵盼龙
 * @createtime：2018/4/11 15:09
 */
public class Api {

    public static final int READ_TIME_OUT = 76760;
    public static final int CLIENT_TIME_OUT = 76760;
    private static HashMap<Class, Api> hashMap = new HashMap<>();


    private <T> T create(Class<T> clazzServer) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(READ_TIME_OUT, TimeUnit.MILLISECONDS)
                .connectTimeout(CLIENT_TIME_OUT, TimeUnit.MILLISECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(getFactory(clazzServer))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(getBaseUrl(clazzServer))
                .build();
        return retrofit.create(clazzServer);
    }


    private String getBaseUrl(Class clazz) {
        try {
            Field urlField = clazz.getField("URL");
            return (String) urlField.get(clazz);
        } catch (Exception e) {
            throw new NullPointerException("APIServer中的URL缺失");
        }
    }

    public Converter.Factory getFactory(Class clazz) {
        try {
            Field factoryField = clazz.getField("FACTORY");
            return (Converter.Factory) factoryField.get(clazz);
        } catch (Exception e) {
            return GsonConverterFactory.create();
        }
    }


    public static <T> T getServer(Class<T> clazz) {
        Api api = hashMap.get(clazz);
        if (api == null) {
            api = new Api();
            hashMap.put(clazz, api);
        }
        return api.create(clazz);
    }

    private HttpLoggingInterceptor getHttpLogIntercptor() {
        //日志显示级别
        HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                LogUtils.i("okhttp==message:" + message);
            }
        });
        interceptor.setLevel(level);
        return interceptor;
    }
}
